<?php 
namespace app\home\controller;
use think\Controller;
class Category extends Common
{
    public function _initialize(){
        parent::_initialize();
    }
	public function index(){
		$id=request()->route('id');
		$data=db('category')->find($id);
		$data['articlelist']=db('article')->where('catid','=',$id)->select();
		$child=db('category')->where('parentid','=',$id)->select();
		foreach ($child as $key => $value) {
			$child[$key]['articlelist']=db('article')->where('catid','=',$value['id'])->select();
		}
		$data['child']=$child;
		return $this->fetch('',$data);
	}
	public function test(){
		$list=db('article')->select();
		$filename=date('Y-m-d_his').'.cvs';
		$tileArray=['标题','介绍','链接'];
		//$tileArray=explode(',', iconv("utf-8", "gb2312","标',介绍,链接"));
		$data=[];
		foreach ($list as $key => $value) {
/*			foreach ($value as $key => $vv) {
				$value[$key]=iconv("utf-8", "gb2312", $vv);
			}*/
			$data[]=[$value['title'],$value['description'],$value['fromlink']];
		}
		$this->exportToExcel($filename,$tileArray,$data);
	}
	/** 
	* @creator Jimmy 
	* @data 2018/1/05 
	* @desc 数据导出到excel(csv文件) 
	* @param $filename 导出的csv文件名称 如date("Y年m月j日").'-test.csv' 
	* @param array $tileArray 所有列名称 
	* @param array $dataArray 所有列数据 
	*/
    public  function exportToExcel($filename, $tileArray=[], $dataArray=[]){
    	foreach ($tileArray as $key => $value) {
    		$tileArray[$key]=iconv("utf-8", "gb2312",$value);
    	}
    	foreach ($dataArray as $k1 => $v1) {
    		foreach ($v1 as $k2 => $v2) {
    			$dataArray[$k1][$k2]=iconv("utf-8", "gb2312",$v2);
    		}
    	}
    	//$tileArray=json_decode(iconv("utf-8", "gb2312",json_encode($tileArray)),true);
    	//$dataArray=json_decode(iconv("utf-8", "gb2312",json_encode($dataArray)),true);
        ini_set('memory_limit','512M');  
        ini_set('max_execution_time',0);  
        ob_end_clean();  
        ob_start();  
        header("Content-Type: text/csv");  
        header("Content-Disposition:filename=".$filename);
        $fp=fopen('php://output','w');  
        fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));//转码 防止乱码(比如微信昵称(乱七八糟的))  
        fputcsv($fp,$tileArray);  
        $index = 0;  
        foreach ($dataArray as $item) {  
            if($index==1000){  
                $index=0;  
                ob_flush();  
                flush();  
            }  
            $index++;  
            fputcsv($fp,$item);  
        }  
  
        ob_flush();  
        flush();  
        ob_end_clean();  
    }
}